#!/bin/bash
# Auto suspend and wake-up script
# This program is used to enter a system sleep state until specified wakeup time
# Puts the computer on standby and automatically wakes it up at specified time
# Takes a 24hour time HH:MM as its argument

function usage()
{
	echo "Usage:suspend_until_wake -t HH:MM"
	echo "----or----"
	echo "Usage:suspend_until_wake -s Hours"
	exit
}
if [ $# -lt 2 ];then
	usage
fi

#Kill rtc if already running
sudo killall rtcwake 2>/dev/null

if [ "$1" = "-t" ]; then

	# Check whether specified time today or tomorrow
	DESIRED=$((`date +%s -d "$2"`))
	NOW=$((`date +%s`))
	if [ $DESIRED -lt $NOW ];then
		DESIRED=$(($DESIRED + 24*60*60))
	fi

	#Set RTC(Real-Time Clock) wakeup time,change "men" for the suspend option find this by "man rtcwake"
	sudo rtcwake -l -m disk -t $DESIRED &

elif [ "$1" = "-s" ]; then
	DESIRED=$(echo "60*60*$2" | bc |awk -F "." '{print $1}')
	sudo rtcwake -l -m disk -s $DESIRED &
else
	echo "Failed..."
	echo
	usage
fi

#feedback and give rtcwake some time to make its stuff
echo "Suspending ..."
sleep 2

#then suspend ,don't usually require this bit
#sudo pm-suspend
#Any commands you want to lanuch after wakeup can be placed here.Remember :sudo may have expired by now
#Wake up with monitor enabled,change "on" for "off" if you want the monitor to be disabled on wake
#xset dpms force on
#and a fresh console
clear
echo "Good morning!"

